package org.mozhu.mboot.backend.system.account.web.controller;

import lombok.extern.slf4j.Slf4j;
import org.mozhu.mboot.backend.AjaxResponse;
import org.mozhu.mboot.backend.security.IdentifiedUserDetails;
import org.mozhu.mboot.backend.system.account.entity.User;
import org.mozhu.mboot.backend.system.account.entity.UserProfile;
import org.mozhu.mboot.backend.system.account.service.UserService;
import org.mozhu.mboot.common.web.controller.BaseCRUDController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends BaseCRUDController<User, Long> {

    @Autowired
    UserService userService;

    @GetMapping("profile")
    public Object getUserProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof IdentifiedUserDetails) {
            IdentifiedUserDetails userDetails = (IdentifiedUserDetails) principal;
            UserProfile userProfile = new UserProfile();
            userProfile.setUserId(userDetails.getId().toString());
            userProfile.setName(userDetails.getUsername());
            userProfile.setRoles(AuthorityUtils.authorityListToSet(userDetails.getAuthorities()));
            userProfile.setAvator((String) userDetails.getDetail("avatar"));
            return AjaxResponse.successWithData(userProfile);
        }
        return AjaxResponse.fail("UserNotFound", "User Not Found");
    }

    @GetMapping("list/invalid/role")
    @PreAuthorize("hasRole('invalid_role')")
    public Object listByInvalidRole() {
        return AjaxResponse.successWithData(userService.findAll());
    }

    @GetMapping("list")
    @PreAuthorize("hasRole('admin')")
    public Object list() {
        return AjaxResponse.successWithData(userService.findAll());
    }

}
